document.addEventListener('DOMContentLoaded', function () {
    function subimt_request(url, data) {
        const form = document.createElement('form');
        form.setAttribute('method', 'POST');
        form.setAttribute('action', url);
        form.setAttribute('style', 'display:none;');
        for (const key in data) {
            const input = document.createElement('input');
            input.setAttribute('type', 'hidden');
            input.setAttribute('name', key);
            input.setAttribute('value', data[key]);
            form.appendChild(input);
        }
        document.body.appendChild(form);
        form.submit();
    }
    document.querySelectorAll('.dic-name').forEach(function (btn) {
        btn.addEventListener('click', () => {
            var fileId = btn.getAttribute('data-fileid');
            var filename = btn.getAttribute('data-name');
            subimt_request(window.location.href, { 'pathid': fileId, 'pathname': filename });
        });
    });
    if (document.querySelector('.file-back') != null) {
        document.querySelector('.file-back').addEventListener('click', () => {
            subimt_request(window.location.href, { 'pathid': '@left-back', 'pathname': '@left-back' });
        });
    }
    document.querySelectorAll('#download_ico_one_file').forEach(function (btn) {
        btn.addEventListener('click', async () => {
            var fileId = btn.getAttribute('data-fileid');
            var filename = btn.getAttribute('data-name');
            var filesizes_bytes = btn.getAttribute('data-sizes');
            var pwd = null;
            const results = await Swal.fire({
                title: 'AuthCode-Pwd',
                input: 'select',
                inputOptions: {
                    'Verify the extraction code': 'Verify the extraction code',
                    'No extraction code': 'No extraction code'
                },
                showCancelButton: true,
                inputValidator: (value) => {
                    return new Promise((resolve) => {
                        if (value === 'Verify the extraction code') {
                            Swal.fire({
                                title: 'Enter AuthCode for PWD',
                                input: 'text',
                                inputPlaceholder: 'Enter code',
                                showCancelButton: true
                            }).then((result) => {
                                if (result.isConfirmed && result.value) {
                                    pwd = result.value;
                                } else {
                                    pwd = '';
                                }
                                newftch_file_pull(fileId, pwd,filesizes_bytes);
                            });
                        } else if (value === 'No extraction code') {
                            pwd = 'no_pwd';
                            resolve();
                        } else {
                            resolve('You must make a selection!');
                        }
                    });
                }
            });

            if (!results.isConfirmed) {
                return;
            }

            if (pwd === null) {
                return;
            }

            async function newftch_file_pull(fileId, pwd,filesizes_bytess) {
                if (pwd === '') {
                    return;
                }
                Qmsg.success('Downloading...', 'Please wait a moment!');
                const progressBar = document.getElementById(`progressbar_${fileId}`);
                progressBar.style.width = '0%';
                try {
                    const response = await fetch(`/files/?${fileId}&pwd=${pwd}`);
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    const contentLength = parseInt(filesizes_bytess);
                    let receivedBytes = 0;
                    if (isNaN(contentLength) || contentLength <= 0) {
                        throw new Error('The download failed!File size is unknown!');
                    }
                    const reader = response.body.getReader();
                    const stream = new ReadableStream({
                        start(controller) {
                            function push() {
                                reader.read().then(({
                                    done,
                                    value
                                }) => {
                                    if (done) {
                                        controller.close();
                                        return;
                                    }
                                    receivedBytes += value.length;
                                    const progress = (receivedBytes / contentLength) * 100;
                                    progressBar.style.width = `${progress.toFixed(2)}%`;
                                    controller.enqueue(value);
                                    push();
                                }).catch(err => {
                                    Swal.fire('Download Failed', err.message, 'error');
                                    controller.close();
                                });
                            }
                            push();
                        }
                    });

                    const newResponse = new Response(stream);
                    const blob = await newResponse.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                    progressBar.style.width = '100%';
                    Swal.fire('Download Complete', 'Download Complete!The file has been saved', 'success');
                } catch (error) {
                    Swal.fire('Download Failed', error.message, 'error');
                }
            }
            newftch_file_pull(fileId, pwd,filesizes_bytes);
        });
    });
    document.querySelectorAll('.progress-container').forEach((container) => {
        let tooltip = null;
        container.addEventListener('mouseenter', function () {
            const progressBar = container.querySelector('.progress-bar');
            if (!progressBar) {
                return;
            }
            const progress = progressBar.style.width;
            tooltip = document.createElement('div');
            tooltip.className = 'custom-tooltip';
            tooltip.style.position = 'absolute';
            tooltip.style.top = `${container.getBoundingClientRect().top + window.scrollY}px`;
            tooltip.style.left = `${container.getBoundingClientRect().right + 10}px`;
            tooltip.style.backgroundColor = '#009688';
            tooltip.style.color = '#fff';
            tooltip.style.padding = '5px 10px';
            tooltip.style.borderRadius = '4px';
            tooltip.style.fontSize = '12px';
            tooltip.style.zIndex = '1000';
            tooltip.textContent = progress;
            document.body.appendChild(tooltip);
            const updateTooltip = () => {
                if (tooltip) {
                    const newProgress = progressBar.style.width;
                    tooltip.textContent = newProgress;
                }
            };
            setInterval(updateTooltip, 500);
        });
        container.addEventListener('mousemove', function (event) {
            if (tooltip) {
                tooltip.style.top = `${event.clientY + 10}px`;
                tooltip.style.left = `${event.clientX + 10}px`;
            }
        });
        container.addEventListener('mouseleave', function () {
            if (tooltip) {
                document.body.removeChild(tooltip);
                tooltip = null;
            }
        });
    });
  
        document.querySelectorAll('.file-name-container').forEach(container => {
            container.addEventListener('mouseenter', () => {
                const filenameshow = container.getAttribute('data-name');
                tooltip = document.createElement('div');
                tooltip.className = 'custom-tooltip';
                tooltip.style.position = 'absolute';
                tooltip.style.top = `${container.getBoundingClientRect().top + window.scrollY}px`;
                tooltip.style.left = `${container.getBoundingClientRect().right + 10}px`;
                tooltip.style.backgroundColor = '#009688';
                tooltip.style.color = '#fff';
                tooltip.style.padding = '5px 10px';
                tooltip.style.borderRadius = '4px';
                tooltip.style.fontSize = '12px';
                tooltip.style.zIndex = '1000';
                tooltip.textContent = filenameshow;
                document.body.appendChild(tooltip);
            });
            container.addEventListener('mousemove', function (event) {
                if (tooltip) {
                    tooltip.style.top = `${event.clientY + 10}px`;
                    tooltip.style.left = `${event.clientX + 10}px`;
                }
            });
            container.addEventListener('mouseleave', function () {
                if (tooltip) {
                    document.body.removeChild(tooltip);
                    tooltip = null;
                }
            });
        });
    });
    function fetch_reason_report_submit(datas){
        fetch('/apicommand/reportnew/', {
            method: 'POST', 
            headers: {
                'Content-Type': 'application/json' 
            },
            body: JSON.stringify(datas) 
        })
            .then(response => {
                if (!response.ok) { 
                    throw new Error('Network response was not ok: ' + response.statusText);
                }
                return response.json(); 
            })
            .then(data => {
                if(data.success){
                    Swal.fire('Success', 'Report submitted successfully!', 'success');
                }else{
                    Swal.fire('Error', 'Report submission failed!', 'error');
                }
            })
            .catch(error => {
                Swal.fire('Error', error.message, 'error');
            });
    }
    document.querySelectorAll('#report_ico_one_file').forEach((item) => {
        item.addEventListener('click', function () {
            var userid = sessionStorage.getItem('user');
            if(userid === null || userid === undefined) {
                Swal.fire('Error', 'Please login first!', 'error');
                return;
            }
            if(_session_token_encdio === null || _session_token_encdio === undefined) {
                Swal.fire('Error', 'Please login first!', 'error');
                return;
            }
            const item2 = item.parentElement.querySelectorAll('i')[0];
            var file_name_o = item2.getAttribute('data-name');
            var file_ids_o = item2.getAttribute('data-fileid');
            let pathname = window.location.pathname;
            let beuserid = pathname.split('/').pop();
            Swal.fire({
                title: 'Please enter the reason for your report',
                input: 'textarea',
                inputPlaceholder: '10 to 200 words',
                showCancelButton: true,
                confirmButtonText: 'Submit',
                cancelButtonText: 'Cancel',
                inputValidator: (value) => {
                  if (!value) {
                    return 'The reason cannot be empty!';
                  }
                  if (value.length < 10) {
                    return 'The reason cannot be less than 10 words!';
                  }
                  if (value.length > 200) {
                    return 'The reason cannot be more than 200 words!';
                  }
                }
              }).then((result) => {
                if (result.isConfirmed) {
                    var userinputent = result.value;
                    var data = {
                        userid: userid,
                        beuserid: beuserid,
                        file_name: file_name_o,
                        file_ids: file_ids_o,
                        reason: userinputent,
                        token: _session_token_encdio
                    };
                    fetch_reason_report_submit(data);
                }
              });
        });
    });
    document.querySelectorAll('.notice-item').forEach((item) => {
        item.addEventListener('click', function () {
            const title = item.querySelector('.notice-name').getAttribute('data-cs');
            const content = item.querySelector('.notice-date').getAttribute('data-cs');
            Swal.fire({
                title: title,
                html: content,
                showCloseButton: true,
                confirmButtonText: 'Close',
            });
        });
    });